//
//  PayMoneyController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/8/23.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "PayMoneyController.h"
#import "OrderPaymentCell.h"
#import "PayMoneyTextCell.h"
#import "CreatStochasticOrderNumber.h"
#import "AliPayOrder.h"
#import "WXApi.h"
#import "WXApiRequestHandler.h"
#import "OrderSuccessViewController.h"
#import "BaseNavigationController.h"

@interface PayMoneyController ()<UITextFieldDelegate>
{
    UITextField *_moneyField;
    UIView *_footView;
    NSInteger PayType;
    NSString *_orderNumber;
}

@property(nonatomic,strong)NSMutableArray *boolArray;

@property (nonatomic,strong)NSDictionary *userInfoDict;
@property(nonatomic,strong)UIButton  *enabledBtn;

@end

@implementation PayMoneyController

- (NSMutableArray *)boolArray
{
    if (!_boolArray) {
        _boolArray = [NSMutableArray arrayWithObjects:@"0",@"1",@"0", nil];
    }
    return _boolArray;
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    [self loadUserInfoNumberData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = BACKGROUND_COLOR;
    self.title = @"充值";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"PayMoneyTextCell" bundle:nil] forCellReuseIdentifier:@"PayMoneyTextCell"];
    self.tableView.scrollEnabled = NO;
    
    PayType = 1;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processOrderWithWXOnPaymentResult:) name:@"processOrderWithWXOnRespPaymentResult" object:nil];
    //    [self payViewSetupUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processAliPayOrderWithPaymentResult:) name:@"processOrderWithPaymentResult" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(judgeWeChatBackDataPayType:) name:@"WeChatType" object:nil];
}


#pragma mark>>>>>>>>DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 2;
    }else if (section == 1){
        return 1;
    }else{
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier= @"payCell";
    
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    
    NSDictionary *dataDict = self.userInfoDict[@"data"];
    
    if (cell==nil) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = FONT(15);
        cell.detailTextLabel.font = FONT(15);
    }
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            cell.textLabel.text = @"充值账户";
            cell.detailTextLabel.text = USERNAME;
            return cell;
        }else{
            cell.textLabel.text = @"账户余额";
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@元",dataDict[@"yue"]];
            if (self.userInfoDict == nil) {
                cell.detailTextLabel.text = @"";
            }
            
            return cell;
        }
        
    }else if (indexPath.section ==1){
        
        PayMoneyTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PayMoneyTextCell" forIndexPath:indexPath];
        _moneyField = cell.PayTextField;
        cell.PayTextField.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.PayTextField.keyboardType = UIKeyboardTypeNumberPad;
        
        return cell;
        
    }else{
        
        if (indexPath.row == 0) {
            cell.textLabel.text = @"支付方式:";
            return cell;
        }else{
            
            static NSString *OrderPaymentCellID= @"paySdkCell";
            
            OrderPaymentCell *cell=[tableView dequeueReusableCellWithIdentifier:OrderPaymentCellID];
            
            if (cell==nil) {
                cell= [[[NSBundle mainBundle] loadNibNamed:@"OrderPaymentCell" owner:nil options:nil] lastObject];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            }
            
            if ([self.boolArray[indexPath.row] isEqualToString:@"1"]) {
                cell.selectImg.image = [UIImage imageNamed:@"shoujichongzhi_0"];
            } else {
                cell.selectImg.image = [UIImage imageNamed:@"shoujichongzhi_1"];
            }
            
            if (indexPath.row == 1) {
               cell.selectIcon.image = [UIImage imageNamed:[NSString stringWithFormat:@"dingdanzhifu_3"]];
            }
            
            if (indexPath.row == 2){
                cell.selectIcon.image = [UIImage imageNamed:[NSString stringWithFormat:@"dingdanzhifu_4"]];
            }
            
            NSArray *arr = @[@"",@"微信"];
            cell.payTittle.text = [NSString stringWithFormat:@"%@",arr[indexPath.row]];
            return cell;
        }
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [_moneyField resignFirstResponder];
    
    if (indexPath.row == 0) {
        return;
    }
    
    
    PayType = indexPath.row;
    
  
    NSLog(@"%ld",PayType);
    
    if (indexPath.section == 2 && indexPath.row > 0) {
        for (NSInteger i=0; i<self.boolArray.count; i++) {
            if (indexPath.row == i) {
                self.boolArray[i] = @"1";
            }else{
                self.boolArray[i] = @"0";
            }
        }
    }
    
    [self.tableView reloadData];
    
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 5;
    }else{
        return 10;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section ==0 || section == 1) {
        return 0.01;
    }else{
        return HEIGHT/10;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    if (section == 0 || section == 1) {
        return nil;
    }else{
        
        _footView = [[UIView alloc]initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT/10)];
        UIButton *rechargeBtn = [[UIButton alloc] init];
        [rechargeBtn setTitle:@"立即充值" forState:UIControlStateNormal];
        [_footView addSubview:rechargeBtn];
        rechargeBtn.layer.cornerRadius = 5;
        rechargeBtn.titleLabel.font = [UIFont systemFontOfSize:18];
        rechargeBtn.layer.masksToBounds = YES;
        [rechargeBtn setBackgroundColor:DEFAULT_COLOR];
        self.enabledBtn = rechargeBtn;
        
        [rechargeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.width.mas_equalTo(WIDTH-30);
            make.centerY.equalTo(_footView.mas_centerY).offset(35/2);
            make.left.equalTo(_footView.mas_left).offset(15);
            make.height.mas_equalTo(40);
        }];
        
        [rechargeBtn addTarget:self action:@selector(rechargeBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
        return _footView;
    }
}



- (void)rechargeBtnDidClick
{
    [_moneyField resignFirstResponder];
    
    if (![_moneyField.text length]) {
        //弹框
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"请输入金额" toView:self.view dimBackground:NO AndCompleteBlock:nil];
        [hud show:YES];
        return;
    }
    
    //请求过程中禁止点击
    self.enabledBtn.enabled = false;
    [self.enabledBtn setBackgroundColor:[UIColor lightGrayColor]];
    
    NSString *_payType;
    if (PayType == 1) {
        _payType = @"4";
    } else {
        _payType = @"3";
    }
    
    NSLog(@"%@",_moneyField.text);
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSDictionary *params = @{
                                 @"username":USERNAME,
                                 @"business_type":@"recharge_money",
                                 @"money":_moneyField.text,
                                 @"payType":_payType
                                 };
        
//        http://www.dev.ylgw8.com/api/Order/createOrderId?username=18000000000&business_tpye=recharge_money&money=10
        
        
        
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Order/createOrderId" completeBlock:^(id object) {
            
            NSLog(@"%@",object);
            
            if (JudgeBackDataCode) {
                NSString *orderNumber = [object objectForKey:@"data"];
                NSLog(@"%@",orderNumber);
                _orderNumber = orderNumber;
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    if (PayType == 1) {
                         NSLog(@"微信");
                        
                         NSString *price = [NSString stringWithFormat:@"%.0f",_moneyField.text.floatValue * 100];
                         [WXApiRequestHandler jumpToWxPayWithOrderNumber:orderNumber andOrderBodyString:@"账户充值" OrderPriceString:price andView:self.view];
                        
                    } else {
                        NSLog(@"支付宝");
                        
//                        [AliPayOrder doAlipayPayWithOrderNumber:orderNumber andOrderAllPrice:_moneyField.text andOrderBodyTitle:@"账户充值" andOrderSubject:@"账户充值" andBackDataBlock:^(id object) {
//                            
//                            if ([object[@"resultStatus"] isEqualToString:@"9000"]) {
//                                
//                                NSString *aliPayString = [object objectForKey:@"result"];
//                                NSDictionary *dict = [self dictionaryWithJsonString:aliPayString];
//                                OrderSuccessViewController *orderSuccess = [[OrderSuccessViewController alloc] init];
//                                orderSuccess.orderNumber = orderNumber;
//                                orderSuccess.creatOrderTime = [dict[@"alipay_trade_app_pay_response"] objectForKey:@"timestamp"];;
//                                orderSuccess.orderType = @"4";
////                                BaseNavigationController *base = [[BaseNavigationController alloc] initWithRootViewController:orderSuccess];
////                                [base pushForm:base pushToAndHidden:orderSuccess];
//                                [self.navigationController pushForm:self.navigationController pushToAndHidden:orderSuccess];
                        
//                            } else {
//                                
//                                NSString *string = [object objectForKey:@"memo"];
//                                
//                                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                                    if (string.length) {
//                                        MBProgressHUD *hud = [MBProgressHUD showMessage:object[@"memo"] toView:self.view dimBackground:NO AndCompleteBlock:nil];
//                                        [self.view addSubview:hud];
//                                    } else {
//                                        MBProgressHUD *hud = [MBProgressHUD showMessage:@"您尚未支付成功" toView:self.view dimBackground:NO AndCompleteBlock:nil];
//                                        [self.view addSubview:hud];
//                                    }
//                                    
//                                });
//                            }
//
//                        } andMBPView:self.view];
                    }
                    
                });
            } else if ([[NSString stringWithFormat:@"%@",object[@"code"]] isEqualToString:@"-9000"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSDictionary *MessageDict = [object objectForKey:@"message"];
                    
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:MessageDict[@"view"] message:nil preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        MyAccountTableViewController *accountVC = [[MyAccountTableViewController alloc] init];
                        [self.navigationController pushForm:self.navigationController pushToAndHidden:accountVC];
                    }];
                    [alert addAction:SettingAction];
                    
                    
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        
                    }];
                    [alert addAction:cancelAction];
                    
                    [self presentViewController:alert animated:YES completion:nil];
                    
                });
            } else {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSDictionary *message = [object objectForKey:@"message"];
                    
                    MBProgressHUD *hud = [MBProgressHUD showMessage:message[@"view"] toView:self.view dimBackground:NO AndCompleteBlock:nil];
                    [hud show:YES];
                    
                });
            }
            
        }];
        
        //请求完成后
        self.enabledBtn.enabled = true;
        [self.enabledBtn setBackgroundColor:DEFAULT_COLOR];
        
    });
    
}

#pragma mark>>>>>>>> 微信返回状态处理
- (void)processOrderWithWXOnPaymentResult:(NSNotification *)notifica {
    BaseResp *resp = notifica.object;
    
    if([resp isKindOfClass:[PayResp class]]){
        
        //支付返回结果，实际支付结果需要去微信服务器端查询
        NSString *strMsg;
        
        switch (resp.errCode) {
            case WXSuccess:
                strMsg = @"支付成功！";
                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                [self WeChatPayControllerPushTuOrderSuccess];
                return;
                break;
                
            case WXErrCodeCommon:
                strMsg = @"支付错误，请稍后再试";
                break;
                
            case WXErrCodeUserCancel:
                strMsg = @"尚未支付成功";
                break;
                
            case WXErrCodeSentFail:
                strMsg = @"发送失败，请稍后再试";
                break;
                
            case WXErrCodeAuthDeny:
                strMsg = @"授权失败，请稍后再试";
                break;
                
            default:
                strMsg = @"微信不支持";
                break;
        }
        
        if (resp.errCode == 0) {
#warning 微信返回接口逻辑
        }
        
        MBProgressHUD *hud = [MBProgressHUD showMessage:strMsg toView:self.view dimBackground:NO AndCompleteBlock:nil];
        [self.view addSubview:hud];
        
    }
}

- (void)judgeWeChatBackDataPayType:(NSNotification *)backData {
    BaseResp *resp = backData.object;
    
    NSString *strMsg=[NSString stringWithFormat:@"errcode:%d",resp.errCode];
    NSString *strTitle;
    if ([resp isKindOfClass:[PayResp class]]) {
        //支付返回结果，实际支付结果需要去微信服务器端查询
        strTitle=[NSString stringWithFormat:@"支付结果"];
        switch (resp.errCode) {
            case WXSuccess:
                strMsg = @"支付成功！";
                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                [self WeChatPayControllerPushTuOrderSuccess];
                return;
                break;
                
            case WXErrCodeCommon:
                strMsg = @"支付错误，请稍后再试";
                break;
                
            case WXErrCodeUserCancel:
                strMsg = @"尚未支付成功";
                break;
                
            case WXErrCodeSentFail:
                strMsg = @"发送失败，请稍后再试";
                break;
                
            case WXErrCodeAuthDeny:
                strMsg = @"授权失败，请稍后再试";
                break;
                
            default:
                strMsg = @"微信不支持";
                break;
        }
        
        MBProgressHUD *hud = [MBProgressHUD showMessage:strMsg toView:self.view dimBackground:NO AndCompleteBlock:nil];
        [self.view addSubview:hud];
    }
}

- (void)WeChatPayControllerPushTuOrderSuccess {
    
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    
    OrderSuccessViewController *orderSuccess = [[OrderSuccessViewController alloc] init];
    orderSuccess.orderNumber = _orderNumber;
    orderSuccess.creatOrderTime = dateString;
    orderSuccess.orderType = @"5";
    [self.navigationController pushForm:self.navigationController pushToAndHidden:orderSuccess];
    
}

#pragma mark>>>>>>>> 支付宝状态处理
- (void)processAliPayOrderWithPaymentResult:(NSNotification *)notifica {
    
    NSDictionary *dict = notifica.object;
    
    NSLog(@"%@",dict);
    
    NSString *aliPayString = [dict objectForKey:@"result"];
    
    if ([dict[@"resultStatus"] isEqualToString:@"9000"]) {
        
        MBProgressHUD *hud = [MBProgressHUD showMessage:@"交易成功" toView:self.view dimBackground:NO AndCompleteBlock:nil];
        [self.view addSubview:hud];
        
        NSLog(@"%@",[self dictionaryWithJsonString:aliPayString]);
        
        NSDictionary *alipay_trade_app_pay_response = [self dictionaryWithJsonString:aliPayString];
        
        [self judgeAliPayBackDataCode:[alipay_trade_app_pay_response objectForKey:@"alipay_trade_app_pay_response"]];
        
        [self.navigationController popToRootViewControllerAnimated:YES];
    } else {
        
        NSString *string = [dict objectForKey:@"memo"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (string.length) {
                MBProgressHUD *hud = [MBProgressHUD showMessage:dict[@"memo"] toView:self.view dimBackground:NO AndCompleteBlock:nil];
                [self.view addSubview:hud];
            } else {
                MBProgressHUD *hud = [MBProgressHUD showMessage:@"您尚未支付成功" toView:self.view dimBackground:NO AndCompleteBlock:nil];
                [self.view addSubview:hud];
            }
            
        });
    }
}

- (void)judgeAliPayBackDataCode:(NSDictionary *)paramsDict {
    
//    NSDictionary *params = @{
//                             @"out_trade_no":paramsDict[@"out_trade_no"],
//                             @"trade_no":paramsDict[@"2016091021001004560262715391"],
//                             @"trade_status":paramsDict[@"code"],
//                             @"notify_time":paramsDict[@"notify_time"],
//                             @"app_id":paramsDict[@"app_id"]
//                             };
//    
//    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Pay/alipayNotity" completeBlock:^(id object) {
//        NSLog(@"%@",object)
//    }];
}



- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    
    if(err) {
        
        NSLog(@"json字典解析失败：%@",err);
        
        return nil;
    }
    
    return dic;
    
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"processOrderWithPaymentResult" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"processOrderWithWXOnRespPaymentResult" object:nil];
}


- (void)loadUserInfoNumberData {
    
    NSDictionary *params = @{
                             @"username":USERNAME
                             };
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"api/User/info" completeBlock:^(id object) {
        self.userInfoDict = object;
        [self.tableView reloadData];
    }];
}


@end
